#!/usr/bin/env bash
set -e

BASEDIR=$PWD
ROOTFS=$BASEDIR/ROOTFS

PYTHON_PREFIX_DIR=`python3 -c 'import sys; print(sys.prefix)'`
PYTHON_MAJOR_VERSION=`python3 -c 'import sys; print(sys.version_info.major)'`
PYTHON_MINOR_VERSION=`python3 -c 'import sys; print(sys.version_info.minor)'`
PYTHON_VERSION="${PYTHON_MAJOR_VERSION}.${PYTHON_MINOR_VERSION}"
PYTHON_MODULES="" #put additional modules here. Example: "django mysql mysql.connector"


install_shlibs() {
SHLIBS=""
SHLIBS+=" $ROOTFS/python.so "
SHLIBS+=" `find $ROOTFS -iname '*\.so' | grep -v '/site-packages/'` "
set +e
SHLIBS+=" `find $ROOTFS -iname '*\.so[\.0-9]*' | grep -v '/site-packages/'` "
set -e
SHLIBS_COUNT="`echo \"$SHLIBS\" | wc -l`"

ldd $SHLIBS | grep -Po '(?<=> )/[^ ]+' | sort | uniq | grep -Pv 'lib(c|gcc|dl|m|util|rt|pthread|stdc\+\+|selinux|krb5|gssapi_krb5)\.so' | xargs -I {} install  {} $ROOTFS/usr/lib
# ROOTFS/lib/python3.7/config/libpython3.7.so is a symlink to ../../libpython3.7.so,
# so create a valid destination to avoid ldd error due to dangling symlink.
(cd $ROOTFS/lib && ln -sf ../usr/lib/libpython${PYTHON_VERSION}m.so.1.0 libpython${PYTHON_VERSION}m.so)
echo "$SHLIBS_COUNT"
}

get_paths() {
python3 - <<'EOF' "$1"
import sys

unique_paths = set([])

#import all additional modules
for mod in sys.argv[1].split():
  try:
    exec('import ' + mod)
    if str(eval(mod + '.__file__')[-12:]) != '/__init__.py':
      unique_paths.add(eval(mod + '.__file__'))
    else:
      unique_paths.add(eval(mod + '.__path__[0]'))

  except NameError:  #module not imported. Try to import
    raise Exception("You misspelled the module name")
  except AttributeError:
    pass  #built-in modules don't have __file__

print(" ".join(unique_paths))

EOF
}


main() {
mkdir -p build/
gcc -o build/python.so python.c -fPIC -shared -lpython${PYTHON_VERSION}m

rm -rf "$ROOTFS"
mkdir -p "$ROOTFS/usr/lib"
mkdir -p "$ROOTFS/lib/python${PYTHON_VERSION}"

cp build/python.so "$ROOTFS"
install_shlibs
for dir in ${PYTHON_PREFIX_DIR}/lib*/python${PYTHON_VERSION}/
do
    rsync -a "$dir" $ROOTFS/lib/python${PYTHON_VERSION}/ --safe-links --exclude test --exclude unittest \
    --exclude '*.pyc' --exclude '*.pyo' --exclude '*.egg-info' --exclude 'site-packages' --exclude 'dist-packages' --exclude '*.a'
done

for i in $(get_paths "${PYTHON_MODULES}")
do
    rsync -a "$i" $ROOTFS/lib/python${PYTHON_VERSION}/ --safe-links \
    --exclude '*.pyc' --exclude '*.pyo' --exclude '*.egg-info'
done

SHLIBS_COUNT4=`install_shlibs`
echo "Python SHLIBS_COUNT4=$SHLIBS_COUNT4"
SHLIBS_COUNT3=`install_shlibs`
echo "Python SHLIBS_COUNT3=$SHLIBS_COUNT3"
SHLIBS_COUNT2=`install_shlibs`
echo "Python SHLIBS_COUNT2=$SHLIBS_COUNT2"
SHLIBS_COUNT1=`install_shlibs`
echo "Python SHLIBS_COUNT1=$SHLIBS_COUNT1"
if [ $SHLIBS_COUNT1 -ne $SHLIBS_COUNT2 ]
then
	# if this happens, just add additional calls to install_shlibs()
	echo "ERROR some libraries required by python might be missing"
	exit 1
fi

#replace sqlite with a non-MREMAP version
cp $BASEDIR/../sqlite/libsqlite3.so.0 $ROOTFS/usr/lib/libsqlite3.so.0
}

main
